<?php

/**
 * @Author: wuchenge
 * @Date:   2021-12-10 18:04:12
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Models;

use DB;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{

    // 状态
    const STATUS_YES = 1;
    const STATUS_NO  = 2;

    /**
     * 按时间排序；最近的
     * @param  [type] $query [description]
     * @return [type]        [description]
     */
    public function scopeRecent($query)
    {
        return $query->orderBy('created_at', 'desc');
    }

    /**
     * 批量插入或更新表中数据
     *
     * @param $data 要插入的数据，元素中的key为表中的column，value为对应的值
     * @param string $table 要插入的表
     * @param array $columns 要更新的的表的字段
     * @return array
     */
    public static function batchInsertOrUpdate($data, $table = '', $columns = [])
    {

        //如果传入数据为空 则直接返回
        if (empty($data)) {
            return [
                'insertNum' => 0,
                'updateNum' => 0,
            ];
        }

        //拼装sql
        $sql = "insert into " . $table . " (";
        foreach ($columns as $column) {
            $sql .= $column . " ,";
        }
        $sql = trim($sql, ',');
        $sql .= " ) values ";

        foreach ($data as $v) {
            $sql .= "(";
            foreach ($columns as $column) {
                if ('updated_at' == $column) {
                    //如果库中存在，create_at字段会被更新
                    $sql .= " '" . date('Y-m-d H:i:s') . "' ,";
                } else {
                    $val = ''; //插入数据中缺少$colums中的字段时的默认值
                    if (isset($v[$column])) {
                        $val = $v[$column];
                        $val = addslashes($val); //在预定义的字符前添加反斜杠的字符串。
                    }
                    $sql .= " '" . $val . "' ,";
                }
            }
            $sql = trim($sql, ',');
            $sql .= " ) ,";
        }
        $sql = trim($sql, ',');
        $sql .= "on duplicate key update ";
        foreach ($columns as $column) {
            $sql .= $column . " = values (" . $column . ") ,";
        }
        $sql = trim($sql, ',');
        $sql .= ';';

        $columnsNum = count($data);
        $retNum     = DB::update(DB::raw($sql));
        $updateNum  = $retNum - $columnsNum;
        $insertNum  = $columnsNum - $updateNum;
        return [
            'insertNum' => $insertNum,
            'updateNum' => $updateNum,
        ];
    }

    /**
     * 获取模型列表数据
     * @param  [array]  $field [字段]
     * @param  [array]  $where [条件]
     * @param  integer  $page  [页码]
     * @param  integer  $limit [条数]
     * @param  array    $order [排序]
     * @param  array    $with  [关联关系]
     * @return [array]         [description]
     */
    public static function lists(
        array $field,
        array $where,
        int $page = 1,
        int $limit = 10,
        array $order = [],
        array $with = []
    ): array {
        // 实例
        $model = self::select($field);

        // 关联关系
        if (!empty($with)) {
            $model->with($with);
        }

        // 条件
        if ($where) {
            // 正常
            if (array_key_exists('nomal', $where) && !empty($where['nomal'])) {
                $model->where($where['nomal']);
            }

            // 多in条件
            if (array_key_exists('in', $where) && !empty($where['in'])) {
                foreach ($where['in'] as $key => $value) {
                    $model->whereIn($key, $value);
                }
            }

            // 闭包条件
            if (array_key_exists('closure', $where)) {
                foreach ($where['closure'] as $value) {
                    $model->where($value);
                }
            }
        }
        
        // 统计
        $total = $model->count();
        if ($total === 0) {
            return [
                'total' => 0,
                'lists' => [],
            ];
        }
        // 排序
        if ($order) {
            foreach ($order as $key => $value) {
                $model->orderBy($key, $value);
            }
        }

        // 查找所有
        if ($page !== 0) {
            // 偏移
            $skip = ($page - 1) * $limit;
            $model->skip($skip)->limit($limit);
        }

        // 结果
        $lists = $model->get()->toArray();

        return [
            'total' => $total,
            'lists' => $lists,
        ];
    }
}
